余烬缀记

NodeJS 定时器里面的 ref 和 unref 方法

edited on:

# NodeJS 定时器里面的 ref 和 unref 方法

Nodejs 的定时器返回的是一个对象,和浏览器的不一样

返回的定时器对象包含hafRefrefrefreshunref方法

调用 ref() 将恢复激活状态,前提是调用了 unref() 停止了,否则无效果

refresh() 方法是将定时器重新启动一次

当 setTimeout 调用时,默认是激活状态的,需要事件循环保持活动状态直至该定时器执行完成后结束,hasRef 返回为 true

当调用 unref() 后,该 timer 处于停止状态,如果没有其他活动事件事件循环将会停止,然后退出程序

const timerA = setTimeout(() => {
  console.log('will i run ?')
}, 700)
// 输出 will i run ?
timerA.unref()
// 无任何输出
//setImmediate(() => {
//  timerA.ref()
//})
// 输出 will i run ?
const timerB = setTimeout(() => {
 console.log('enable')
 // timerA.ref()
}, 300)
// 输出 enable
const timerC = setTimeout(() => {
  console.log('end')
}, 800)
// 输出 will i run ?
// 输出 end
  • 如果没有其他活动事件,例如 setTimeout 等待时间超过当前事件的,程序将会退出。如果回调函数未执行将不会被执行
  • 如果有其他活动事件的,比如下面的 800 毫秒的 timerC,那么 timerA 的回调函数将会执行